<?php

namespace app\logic\yuql;

use app\api\model\yuql\Cashe;
use app\api\model\yuql\Order;
use app\api\model\yuql\Rebate;

class DistributionLogic
{

    /**
     * yuql
     * 根据用户订单id查询订单信息，入返佣库
     * @param $params
     * @throws \Exception
     */
    public static function goodsOrderStatus($params)
    {
        if (empty($params['uid'])) throw new \Exception('用户id为空');
        //查询此用户所有支付成功的订单商品
        $userGoodsOrderAll = Order::goodsOrders(['uid' => $params['uid'], 'pay_status' => 1, 'status' => 1]);
        if (!$userGoodsOrderAll) throw new \Exception('此用户没有支付过任何商品,或商品已处理');

        $uid = $userGoodsOrderAll[0]['uid'];
        $userOne = Rebate::userOne(['id' => $uid]);
        $userPidOne = Rebate::userOne(['id' => $userOne['pid']]);
        if (!$userPidOne) throw new \Exception('没有上级用户');
        $rebateMoney = Rebate::rebateMoney(['uid' => $uid]);
        foreach ($rebateMoney as $v) {
            $remoney = $v['re_money'];
            $remoneyAll[] = $remoney;
            //计算此用户卖出所有商品的所有返佣金
            $moneySum = 0;
            foreach ($remoneyAll as $val) {
                $moneySum += $val;
            }
        }
        //计算用户和上级用户分销的金额
        $DistriMonryPro = $moneySum * 0.5;
        //修改上级用户的库存金额
        $userRebatePidOne = Rebate::userPresentOne(['uid' => $userPidOne['id']]);
        $userRebatePidOne['cash_money'] += $DistriMonryPro;
        $userPidMoneySet = Rebate::userPidMoneySet(['uid' => $userRebatePidOne['uid']], $userRebatePidOne['cash_money']);
        if (!$userPidMoneySet) throw new \Exception('分佣失败');
        OrderLogic::userOrderStatusUp(['uid' => $uid, 'pay_status' => 1], 0);
        //添加当前用户佣金库存
        $userPresentOne = Rebate::userPresentOne(['uid' => $uid]);
        $userPresentMoney = $moneySum - $DistriMonryPro;
        $userPresentOne['cash_money'] += $userPresentMoney;
        $userPresentMoney = Rebate::userPresentMoney(['uid' => $uid], $userPresentOne['cash_money']);
        return $userPresentMoney;
    }

    /**
     * yuql
     * 根据返佣金额
     * @param $params
     * @return array
     * @throws \Exception
     */
    public static function sortList($params)
    {
        if (empty($params)) throw new \Exception('参数为空');
        $newTime = time();
        switch ($params['keyword']) {
            case 'week' :
                $beginTime = $newTime - 60 * 60 * 24 * 7;
                break;
            case 'month' :
                $beginTime = $newTime - 60 * 60 * 24 * 30;
                break;
            case 'year' :
                $beginTime = $newTime - 60 * 60 * 24 * 30 * 12;
                break;
        }
        //根据选择时间范围类的数据进行排序
        $cashesBetTime = Cashe::cashesBetTime('created_time', [$beginTime, $newTime], 'cash_money');
        return $cashesBetTime;
    }
}